const express = require("express");
const router = express.Router();
const ExcelJS = require('exceljs');
const workbook = new ExcelJS.Workbook();
const path=require("path")
const {getUserInfo}=require("../../utils/getUserInfo")
const jwt = require('jsonwebtoken') //服务器签发token的模块
const FilePath=path.resolve(__dirname,'../../public/files')
var userRoutersSchema = require("../../database/model/myCenter/userRoutersModel");
const {initExcel}=require("../nodeExcel/nodeExcelController")
const ipAdress=require("../../utils/getIPAdress")
router.post("/userRoutersInfoList", (req, res) => {
  let { userId,name,label,ownerName } = req.body;
  const filter={
    $and:[
      {
        $or: [
          {
            ownerId: userId,
          },
          {
            ownerName: "system",
          },
          {
            ownerName: "",
          },
        ],
      },
    ]
  }
  name && filter.$and.push({name:name})
  label && filter.$and.push({label:label})
  ownerName && filter.$and.push({ownerName:ownerName})
  userRoutersSchema.find(filter).then((data) => {
    res.send({
      msg: "查询成功",
      code: 1,
      data: data,
    });
  });
});
const initTree = (treeArr) => {
  let defaultArr=[]
  treeArr.forEach((item, index) => {
    if (item.ownerName == "system" && item.isMenu&&item.parentId==0) {
      defaultArr.push(item)
    }
  })
  let recursionTree = function (arr, allRouteArr) {
    let newArr = JSON.parse(JSON.stringify(arr))
    for (let i = 0; i < newArr.length; i++) {
      let childrenList = []
      for (let j = allRouteArr.length-1; j > -1; j--) {//优化算法
        if (allRouteArr[j].parentId == newArr[i]._id) {
          childrenList.push(allRouteArr[j])
          allRouteArr.splice(j,1)//优化算法
        }
      }
      if (childrenList.length > 0) {
        newArr[i].children = recursionTree(childrenList,allRouteArr)
      } else { 
        delete newArr[i].children
      }
    }
    return newArr
  }
  return recursionTree(defaultArr, treeArr)
}
const cursionComponents=(modulesArr,startIndex=0)=>{
  let arr=[]
  modulesArr.forEach((item,index)=>{
    let obj={title:item[startIndex],key:item[startIndex]+'/',parentIndex:-1,itemIndex:startIndex,children:[]}
    let bool=arr.findIndex(item2=>{return item2.title==item[startIndex]})==-1
    bool && arr.push(obj)
  })
  return arr
}
const cursionComponents2=(modulesArr,startIndex,arr)=>{
  let newArr = Object.assign([],arr)
  newArr.forEach(item2 => {
    let childrenList=[]
    modulesArr.forEach((item,index)=>{
      if(item2.title==item[startIndex-1]&&item[startIndex-1]&&item[startIndex]){
        let obj={title:item[startIndex],key:item2.key+item[startIndex],parentIndex:startIndex-1,itemIndex:startIndex,children:[]}
        if(obj.title.indexOf('.vue')==-1){
          obj.key=obj.key+'/'
        }else{
          obj.isLeaf=true
        }
        childrenList.push(obj)
      }
    })
    if (childrenList.length > 0) {
      let number=startIndex+1
      item2.children = cursionComponents2(modulesArr,number,childrenList)
    } else { 
      delete item2.children
    }
  });
  return newArr
}
router.post("/userRouterTree", (req, res) => {
  let { userId } = req.body;
  userRoutersSchema.find({
    $or: [
      {
        ownerId: userId,
      },
      {
        ownerName: 'system',
      },
    ]
  }).then((data) => {
    console.time("a")
    let arr = initTree(data)
    console.timeEnd("a")
    res.send({
      msg: "查询成功",
      code: 1,
      data: arr,
    })
  });
});
router.post("/export",  (req, res) => {
  let { idList } = req.body;
  userRoutersSchema.find({_id:{$in:idList}}).then(async (data) => {
    // console.log(777,data)
    let dataArr=data.map((item,index)=>{
      let arr=[index+1,item.title,item.name,item.path,item.auth,item.hidden?'是':'否',item.isMenu?'是':'否',item.component,item.cache?'是':'否',item.icon,item.parentId,item.parentName]
      return arr
    })
    let headerStyle = {
      font: {
        name : 'Microsoft YaHei',
        bold : true,
        color: { rgb: '000000' },
        sz   : '10'
      },
      alignment: {
        horizontal: 'center',
        vertical: 'center',
      },
      fill  : {
        // patternType:'solid',
        fgColor: { rgb: 'ff8080' },
      },
      border: {
        top   : {
         style: 'thin', color: { rgb: '000000' }
        },
        bottom: {
         style: 'thin', color: { rgb: '000000' }
        },
        left  : {
         style: 'thin', color: { rgb: '000000' }
        },
        right : {
         style: 'thin', color: { rgb: '000000' }
        },
      }
    };
    const query={
      Data:[[{v:'序号',s:headerStyle},'标题','路由名','跳转路径','权限字段','是否隐藏','是否是菜单','组件','是否缓存','图标','父级ID','父级名称'],...dataArr],
      fileName:'路由数据' 
    }
    let UUID=await initExcel(query)
    console.log(777,UUID)
    res.send({
      msg: "导出成功",
      code: 1,
      data: 'http://'+`${ipAdress}`+`:3000/temp/${UUID}`,
    })
  });
});
const addUserRouter=(res,data,index)=>{
  if(data.isMenu){
    data.name=data.parentName
    data.path=data.path || '/'
  }
  let staticName=['my','authControl','menuSettings','home','login',]
  if(!data.isMenu&&staticName.indexOf(data.name)!=-1){
    res.status(500).send({
      code:0,
      msg:"新增失败，路由名为关键路由，不可新增"
    })
    return 
  }
  return new userRoutersSchema(data).save().then(res=>{
    console.log(index,888)
  })
}
router.post("/addUserRouter", (req, res) => {
  let data={ ...req.body }
  addUserRouter(res,data).then((data) => {
    res.send({
      code: 200,
      msg: "新增成功",
    });
  }).catch((err) => {
    res.send({
      code: 0,
      msg: err,
    });
  })
});
router.post("/userRouterDetail", async(req, res) => {
  let {id}=req.body
  const token=req.headers.token
  let {_id:userId}=await getUserInfo(token)
  let obj=await userRoutersSchema.find({_id:id})
  res.send({
    msg:"查询详情成功",
    data:obj[0],
    code:1
  })
});
router.post("/systemComponentsTree", (req, res) => {
  let {modulesArr}=req.body
  const systemComponentsTree=cursionComponents2(modulesArr,1,cursionComponents(modulesArr,0))
  res.send({
    data:systemComponentsTree,
    msg:"组件树处理成功",
    code:1
  })
})
router.put("/userRoutersInfo", (req, res) => {
  let data=req.body
  userRoutersSchema.findByIdAndUpdate({_id:data._id},{...data}).then(result=>{
    result && res.send({
      msg:'修改成功',
      code:1
    })
  })
});
router.delete("/userRoutersInfo", (req, res) => {
  let { userId, routerId } = req.body
  if(userId==0){
    res.status(500).send({
      code:0,
      msg:"删除失败，系统权限不可删除"
    })
    return
  }
  userRoutersSchema.remove({
    $and: [
      {ownerId:userId},
      {_id:routerId},
    ]
  }).then((data,err) => {
    !err && res.send(
      {
        code: 200,
        msg: "删除成功",
      }
    )
  })
  
});
router.post("/import",async (req, res) => {
  await workbook.xlsx.readFile(FilePath+path.sep+req.body.fileName);
  const sheet = workbook.worksheets[0];
  const token=req.headers.token
  // let decoded= await jwt.verify(token, 'alsdkjfalsdufioj4654asdfasdf')
  let userInfo=await getUserInfo(token)
  console.log(userInfo,888)
  let newArr=[]
  sheet.eachRow(function (row, rowNumber) {
      let obj={title:row.values[2],name:row.values[3],path:row.values[4],auth:row.values[5],hidden:row.values[6]=='是'?true:false,isMenu:row.values[7]=='是'?true:false,component:row.values[8],cache:row.values[9]=='是'?true:false,icon:row.values[10],parentId:row.values[11],parentName:row.values[12],ownerId:userInfo._id,ownerName:userInfo.username}
      newArr.push(obj)
  });
  newArr.shift()//删除表头数据
  await Promise.all(//2种写法
    newArr.map((item,index)=>{
      return addUserRouter(res,item,index)
    })
  )
  // for(let i=0;i<newArr.length;i++){
  //   await addUserRouter(res,newArr[i],i)
  // }
  res.send({
    code:0,
    msg:"导入成功"
  })
  console.log(1111)
});
module.exports = router;
